package simtools.xml;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Iterator;

import org.jdom.Document;
import org.jdom.Element;

public class SurrogateContent {

	private Document surrogates;
	private Document videoObjects;
	private Element newContent = new Element("Surrogates");

	public Document setContent(Document surrogates, Document videoObjects) {
		this.surrogates = surrogates;
		this.videoObjects = videoObjects;
		
		Map<String, String> videos = getVideos();
		Iterator<Element> surrogateIt = getSurrogate();
		while(surrogateIt.hasNext()) {
			Element root  	   = surrogateIt.next();
			String cacheSize   = root.getChild("CacheSize").getText();
			String cachePolicy = root.getChild("CachePolicy").getText();
			String surrogateId = root.getChild("SurrogateId").getText();
			
			createXML(cacheSize, cachePolicy, surrogateId, videos);
		}

		return new Document(newContent);
	}

	@SuppressWarnings("unchecked")
	private Iterator<Element> getSurrogate() {
		return surrogates.getRootElement().getChildren("Surrogate").iterator();
	}

	@SuppressWarnings("unchecked")
	private Map<String, String> getVideos() {
		Map<String, String> content = new HashMap<String, String>();
		Element root = videoObjects.getRootElement();
		List<Element> contentList = root.getChildren("Object");
		Iterator<Element> i = contentList.iterator();

		while (i.hasNext()) {
			Element linksTemp = i.next();
			String id = linksTemp.getChild("Id").getText();
			String size = linksTemp.getChild("Size").getText();
			content.put(id, size);
		}

		return content;
	}

	private void createXML(String cacheSize, String cachePolicy, String surrogateId, Map<String, String> videos) {
		Element root 	   	   = new Element("Surrogate");
		Element eCacheSize 	   = new Element("CacheSize");
		Element eCachePolicy   = new Element("CachePolicy");
		Element eSurrogateId   = new Element("SurrogateId");
		
		eCacheSize.setText(cacheSize);
		eSurrogateId.setText(surrogateId);
		eCachePolicy.setText(cachePolicy);
		
		Element eObjectsStores = new Element("ObjectsStores");
		Element eObjectId 	   = new Element("ObjectId");
		
		int count = 0;
		int objectId = (int) (Math.random() * (videos.size() - 1));
		count = Integer.parseInt(videos.get(Integer.toString(objectId)).toString());
		while(count < Integer.parseInt(cacheSize) ) {
			Element objectIdTemp = (Element) eObjectId.clone();
			objectIdTemp.setText(Integer.toString(objectId));
			eObjectsStores.addContent(objectIdTemp);
			
			objectId = (int) (Math.random() * (videos.size() - 1));
			count += Integer.parseInt(videos.get(Integer.toString(objectId)).toString());
		}

		root.addContent(eCacheSize);
		root.addContent(eCachePolicy);
		root.addContent(eSurrogateId);
		root.addContent(eObjectsStores);
		
		newContent.addContent(root);
	}
}
